# -*- coding: utf-8 -*-
import os
import sys

base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "base.settings")

from common.lottery.model import TrackIndex
from common.lottery.db import generate_track_detail
from common.lottery.cyclical.model import ORDER_MODEL
from common.lottery.cyclical import ORDER_STATUS, TRACK_STATUS

track_id = sys.argv[1]

track_index = TrackIndex.query.filter(TrackIndex.track_id == track_id).first()
model = ORDER_MODEL[track_index.activity_type]
for order in model.query.filter(model.track_id == track_id).all():
    if order.status != ORDER_STATUS.READY and order.track_status == TRACK_STATUS.READY:
        print('order <%s> status corrupt. status: %s, track_status: %s' % (order.id, order.status, order.track_status))
        if order.status in [ORDER_STATUS.WINNED, ORDER_STATUS.UNCHECK, ORDER_STATUS.FAIL, ORDER_STATUS.SHOW]:
            order.track_status = TRACK_STATUS.WINNED
        if order.status == ORDER_STATUS.LOSE:
            order.track_status = TRACK_STATUS.TRACKED
        if order.status == ORDER_STATUS.CANCEL:
            order.track_status = TRACK_STATUS.CANCEL
        order.save()

ongoing_order = model.query.filter(model.track_id == track_id).filter(model.status == ORDER_STATUS.READY).first()
if not ongoing_order and track_index.status == TRACK_STATUS.READY:
    track_index.status = TRACK_STATUS.TRACKED

generate_track_detail(track_id)
